class Dep {
  constructor() {
    this.subscribers = new Set()
  }

  depend() {
    if (activeEffect) {
      this.subscribers.add(activeEffect)
    }
  }

  notify() {
    this.subscribers.forEach(effect => {
      effect()
    })
  }

}

let activeEffect = null
function watchEffect(effect) {
  activeEffect = effect
  effect()
  activeEffect = null
}

// Map(key: value) key是字符串
// WeakMap(key: valye) : key是一个对象，弱引用
const targetMap = new WeakMap()
function getDep(target, key) {
  // 1.根据对象取出对应map值
  let depMap = targetMap.get(target)
  if (!depMap) {
    depMap = new Map()
    targetMap.set(target, depMap)
  }
  // 2.取出具体的dep对象
  let dep = depMap.get(key)
  if (!dep) {
    dep = new Dep()
    depMap.set(key, dep)
  }
  return dep
}


// vue2 对数据进行劫持
function reactive(raw) {
  Object.keys(raw).forEach(key => {
    const dep = getDep(raw, key)
    let value = raw[key]
    Object.defineProperty(raw, key, {
      get() {
        dep.depend()
        return value
      },
      set(newValue) {
        value = newValue
        dep.notify()
      }
    })
  })
  return raw
}


// 测试代码
const info = reactive({ counter: 100, name: 'aaa' })
const foo = reactive({height: 110})

watchEffect(function () {
  console.log('effct1', info.counter * 2, info.name)
})
watchEffect(function () {
  console.log('effct2',info.counter * info.counter)
})

info.counter++
